package com.cpp.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cpp.bean.Tbl_Account;
import com.cpp.dao.Tbl_Account_DAO;
import com.cpp.util.SinaWeiboUtil;
import com.cpp.util.TokenUtil;

import weibo4j.Oauth;
import weibo4j.http.AccessToken;
import weibo4j.model.User;
import weibo4j.model.WeiboException;
import weibo4j.org.json.JSONObject;

/**
 * Servlet implementation class CallBackServlet
 */
public class CallBackServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CallBackServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String code = request.getParameter("code");
		//System.out.println("code:"+code);
		Oauth oauth = new Oauth();
		try {			
			AccessToken access_token = oauth.getAccessTokenByCode(code);			
			//System.out.println(access_token.getAccessToken());
			request.getSession().setAttribute("token", access_token.getAccessToken());
			User user = new SinaWeiboUtil(access_token.getAccessToken()).showUserById(access_token.getUid());
			request.getSession().setAttribute("user", user);
			Tbl_Account account = new Tbl_Account();
			Tbl_Account_DAO account_DAO = new Tbl_Account_DAO();
			int id = account_DAO.query(access_token.getUid());
			if(id != 0){
				//更新最后登录时间
				account.setId(id);	
				account.setToken(access_token.getAccessToken());
				account.setLogintime(new Date());
				account_DAO.update(account);
			}
			else{
				//插入新用户
				account.setUid(user.getId());
				account.setToken(access_token.getAccessToken());
				account.setLogintime(new Date());
				account.setRegtime(new Date());
				account_DAO.save(account);
			}
			
			TokenUtil.updateToken(access_token.getAccessToken());
			
			response.sendRedirect("./web/sina/index.jsp");
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}

}
